package com.arvin.faceDetect.ui

import android.Manifest
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.camera.core.Camera
import androidx.camera.core.CameraSelector
import androidx.camera.core.FocusMeteringAction
import androidx.camera.core.ImageAnalysis
import androidx.camera.core.ImageProxy
import androidx.camera.core.Preview
import androidx.camera.core.SurfaceOrientedMeteringPointFactory
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import com.arvin.faceDetect.databinding.FragmentFaceDetectionBinding
import com.arvin.faceDetect.db.FaceDatabase
import com.arvin.faceDetect.db.RecognitionRecord
import com.arvin.faceDetect.ml.FaceFeatureExtractor
import com.arvin.faceDetect.model.CameraSettings
import com.arvin.faceDetect.model.RecognizedFace
import com.arvin.faceDetect.ui.adapter.RecognizedFaceAdapter
import com.arvin.faceDetect.utils.FaceQualityChecker
import com.arvin.faceDetect.utils.FeatureQualityAnalyzer
import com.arvin.faceDetect.utils.ImageAnalyzer
import com.arvin.faceDetect.utils.Settings
import com.arvin.faceDetect.utils.toBitmap
import com.google.mlkit.vision.common.InputImage
import com.google.mlkit.vision.face.FaceDetection
import com.google.mlkit.vision.face.FaceDetectorOptions
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.TimeoutCancellationException
import kotlinx.coroutines.async
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeout
import java.util.Date
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.math.abs

class FaceDetectionFragment : Fragment() {
    companion object {
        private const val TAG = "FaceDetectionFragment"
    }

    private var _binding: FragmentFaceDetectionBinding? = null
    private val binding get() = _binding!!

    private var cameraExecutor: ExecutorService? = null
    private var camera: Camera? = null
    private var imageAnalyzer: ImageAnalysis? = null
    private lateinit var faceFeatureExtractor: FaceFeatureExtractor
    private lateinit var recognizedFaceAdapter: RecognizedFaceAdapter
    private var registeredFaces = listOf<com.arvin.faceDetect.db.FaceEntity>()

    // 将通道声明为可空类型
    private var detectionQueue: Channel<Pair<List<com.google.mlkit.vision.face.Face>, android.graphics.Bitmap>>? =
        null
    private var recognitionQueue: Channel<Triple<com.google.mlkit.vision.face.Face, android.graphics.Bitmap, Long>>? =
        null

    // 使用单个原子变量控制整个处理流程
    private val isProcessing = AtomicBoolean(false)
    
    // 添加人脸识别历史记录
    private val recognitionHistory = mutableMapOf<String, MutableList<Float>>()
    private val historyMaxSize = 5 // 保留最近5次的识别结果
    
    // 添加最近识别记录的时间戳映射
    private val lastRecognitionTime = mutableMapOf<String, Long>()

    private var isProcessingFrame = false

    private val requestPermissionLauncher = registerForActivityResult(
        ActivityResultContracts.RequestPermission()
    ) { isGranted ->
        if (isGranted) {
            startCamera()
        } else {
            Toast.makeText(context, "需要相机权限才能进行人脸检测", Toast.LENGTH_SHORT).show()
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentFaceDetectionBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        
        setupRecyclerView()
        
        faceFeatureExtractor = FaceFeatureExtractor(requireContext())
        cameraExecutor = Executors.newSingleThreadExecutor()

        // 初始化通道
        detectionQueue = Channel(Channel.BUFFERED)
        recognitionQueue = Channel(Channel.BUFFERED)

        Log.d("FaceSDK", "开始监听数据库更新")
        
        // 监听已注册的人脸数据
        viewLifecycleOwner.lifecycleScope.launch {
            Log.d("FaceSDK", "启动人脸数据监听协程")
            FaceDatabase.getDatabase(requireContext())
                .faceDao()
                .getAllFaces()
                .collect { faces ->
                    registeredFaces = faces
                    Log.d("FaceSDK", "已注册的人脸数量: ${registeredFaces.size}")
                    registeredFaces.forEach { face ->
                        Log.d("FaceSDK", "注册人脸 - ID: ${face.id}, 姓名: ${face.name}")
                    }
                }
        }

        // 监听最近的识别记录
        viewLifecycleOwner.lifecycleScope.launch {
            Log.d("FaceSDK", "启动识别记录监听协程")
            getLatestRecords().collect { records ->
                Log.d("FaceSDK", "收到记录更新: ${records.size}条")
                records.forEach { record ->
                    Log.d(
                        "FaceSDK",
                        "识别记录 - ID: ${record.id}, 姓名: ${record.name}, 时间: ${Date(record.recognitionTime)}"
                    )
                }
                val recognizedFaces = records.map { record ->
                    RecognizedFace(
                        id = record.id.toString(),
                        name = record.name,
                        confidence = record.similarity,
                        faceBitmap = record.faceBitmap
                    )
                }
                Log.d("FaceSDK", "更新UI显示记录")
                recognizedFaceAdapter.submitList(recognizedFaces)
            }
        }

        // 启动检测处理协程
        val processingJob = viewLifecycleOwner.lifecycleScope.launch(Dispatchers.Default) {
            Log.d("FaceSDK", "启动检测处理协程")
            var consecutiveErrors = 0
            val maxConsecutiveErrors = 3

            try {
                while (isActive) {
                    try {
                        // 检查通道状态
                        val queue = detectionQueue
                        if (queue == null) {
                            Log.e("FaceSDK", "检测通道为空，退出处理循环")
                            break
                        }
                        if (queue.isClosedForReceive) {
                            Log.e("FaceSDK", "检测通道已关闭，退出处理循环")
                            break
                        }

                        // 检查处理状态
                        if (isProcessing.get()) {
                            Log.d("FaceSDK", "当前正在处理中，等待100ms")
                            delay(100)
                            continue
                        }

                        Log.d("FaceSDK", "等待接收检测任务...")
                        val (faces, bitmap) = queue.receive()
                        Log.d("FaceSDK", "成功接收检测任务 - 人脸数量: ${faces.size}")

                        // 检查bitmap是否有效
                        if (bitmap.isRecycled) {
                            Log.e("FaceSDK", "检测到无效的bitmap，跳过处理")
                            continue
                        }

                        // 尝试设置处理状态
                        if (!isProcessing.compareAndSet(false, true)) {
                            Log.d("FaceSDK", "无法设置处理状态，跳过当前任务")
                            continue
                        }

                        Log.d("FaceSDK", "开始处理检测任务")
                        withContext(NonCancellable) {
                            try {
                                faces.forEach { face ->
                                    try {
                                        Log.d("FaceSDK", "处理人脸 ID: ${face.trackingId}")
                                        Log.d("FaceSDK", "开始执行基础检查")
                                        val checkResult = performBasicChecks(face, bitmap)
                                        Log.d("FaceSDK", "基础检查结果: $checkResult")

                                        if (checkResult) {
                                            Log.d(
                                                "FaceSDK",
                                                "基础检查通过，准备调用processRecognition"
                                            )
                                            processRecognition(
                                                face,
                                                bitmap,
                                                System.currentTimeMillis()
                                            )
                                            Log.d("FaceSDK", "processRecognition调用完成")
                                            consecutiveErrors = 0
                                        } else {
                                            Log.d("FaceSDK", "基础检查未通过，跳过当前人脸")
                                        }
                                    } catch (e: Exception) {
                                        Log.e("FaceSDK", "处理单个人脸时发生错误: ${e.message}")
                                        e.printStackTrace()
                                        consecutiveErrors++
                                    }
                                }
                            } catch (e: Exception) {
                                Log.e("FaceSDK", "批量处理人脸时发生错误: ${e.message}")
                                e.printStackTrace()
                                consecutiveErrors++
                            } finally {
                                // 重置处理状态
                                isProcessing.set(false)
                                Log.d("FaceSDK", "任务处理完成，重置处理状态")
                            }
                        }

                        // 处理连续错误
                        if (consecutiveErrors >= maxConsecutiveErrors) {
                            Log.e("FaceSDK", "连续错误次数过多(${consecutiveErrors})，暂停处理")
                            delay(1000)
                            consecutiveErrors = 0
                        }
                    } catch (e: CancellationException) {
                        Log.d("FaceSDK", "检测处理协程被取消")
                        break
                    } catch (e: Exception) {
                        Log.e("FaceSDK", "处理检测任务时发生错误: ${e.message}")
                        e.printStackTrace()
                        consecutiveErrors++
                        isProcessing.set(false)
                    }
                }
            } finally {
                Log.d("FaceSDK", "检测处理协程结束")
                withContext(NonCancellable) {
                    isProcessing.set(false)
                }
            }
        }

        // 监控处理协程的状态
        processingJob.invokeOnCompletion { throwable ->
            if (throwable != null) {
                Log.e("FaceSDK", "处理协程异常结束: ${throwable.message}")
            } else {
                Log.d("FaceSDK", "处理协程正常结束")
            }
        }

        if (allPermissionsGranted()) {
            startCamera()
        } else {
            requestPermissionLauncher.launch(Manifest.permission.CAMERA)
        }
    }

    private fun setupRecyclerView() {
        recognizedFaceAdapter = RecognizedFaceAdapter()

        // 使用GridLayoutManager，设置每行5个，总共显示10个
        val gridLayoutManager = GridLayoutManager(requireContext(), 5)
        // 设置布局方向为从左到右，从上到下
        gridLayoutManager.orientation = GridLayoutManager.VERTICAL
        binding.rvRecognizedFaces.apply {
            layoutManager = gridLayoutManager
            adapter = recognizedFaceAdapter
            setHasFixedSize(true)  // 优化性能
            itemAnimator = null    // 禁用动画以提高性能
        }

        // 计算item大小
        val displayMetrics = resources.displayMetrics
        val screenWidth = displayMetrics.widthPixels
        val itemWidth = (screenWidth / 5) - 16 // 每行5个，减去padding
        val itemHeight = (itemWidth * 1.3).toInt() // 设置合适的宽高比
        recognizedFaceAdapter.updateItemSize(itemWidth, itemHeight)

        // 监听最新记录
        viewLifecycleOwner.lifecycleScope.launch {
            getLatestRecords().collect { records ->
                Log.d(TAG, "收到${records.size}条最新记录")
                val recognizedFaces = records.map { record ->
                    RecognizedFace(
                        id = record.id.toString(),
                        name = record.name,
                        confidence = record.similarity,
                        faceBitmap = record.faceBitmap
                    )
                }
                recognizedFaceAdapter.submitList(recognizedFaces) {
                    // 列表更新完成后滚动到最新项
                    binding.rvRecognizedFaces.scrollToPosition(0)
                }
            }
        }
    }

    private fun startCamera() {
        try {
            Log.d(TAG, "开始启动相机")
            val cameraProviderFuture = ProcessCameraProvider.getInstance(requireContext())
            cameraProviderFuture.addListener({
                try {
                    val cameraProvider = cameraProviderFuture.get()
                    Log.d(TAG, "相机提供者初始化成功")
                    
                    // 获取相机参数
                    val cameraFacing = Settings.getCameraFacing(requireContext())
                    val cameraSelector = when (cameraFacing) {
                        CameraSettings.CAMERA_FACING_FRONT -> CameraSelector.DEFAULT_FRONT_CAMERA
                        CameraSettings.CAMERA_FACING_BACK -> CameraSelector.DEFAULT_BACK_CAMERA
                        else -> CameraSelector.DEFAULT_FRONT_CAMERA
                    }
                    
                    // 设置预览尺寸
                    val targetResolution = Settings.getCameraResolutionSize(requireContext())
                    Log.d(TAG, "目标分辨率: ${targetResolution.width}x${targetResolution.height}")
                    
                    // 设置相机参数
                    val isFrontCamera = cameraFacing == CameraSettings.CAMERA_FACING_FRONT
                    Log.d(TAG, "相机朝向: ${if (isFrontCamera) "前置" else "后置"}")
                    
                    // 绑定用例
                    bindCameraUseCases(cameraProvider)
                } catch (e: Exception) {
                    Log.e(TAG, "相机初始化失败", e)
                }
            }, ContextCompat.getMainExecutor(requireContext()))
        } catch (e: Exception) {
            Log.e(TAG, "启动相机失败", e)
        }
    }

    private suspend fun processRecognition(
        face: com.google.mlkit.vision.face.Face,
        bitmap: android.graphics.Bitmap,
        timestamp: Long
    ) {
        try {
            // 1. 裁剪人脸区域
            val faceBitmap = faceFeatureExtractor.cropFace(bitmap, face.boundingBox)

            // 2. 提取特征
            val features = faceFeatureExtractor.extractFeatures(faceBitmap)
            if (features == null) {
                Log.w(TAG, "特征提取失败")
                return
            }

            // 3. 特征质量评估
            val qualityResult = FeatureQualityAnalyzer.analyzeFeatureQuality(features)
            if (qualityResult.quality != FeatureQualityAnalyzer.FeatureQuality.GOOD) {
                Log.w(TAG, "特征质量不达标: ${qualityResult.quality}")
                return
            }

            // 4. 特征匹配
            val matchResult = performFaceMatching(features, faceBitmap, timestamp)

            // 5. 更新UI
            updateRecognitionResult(matchResult, faceBitmap)
            
        } catch (e: Exception) {
            Log.e(TAG, "人脸识别处理失败: ${e.message}")
        }
    }

    private fun performBasicChecks(
        face: com.google.mlkit.vision.face.Face,
        bitmap: android.graphics.Bitmap
    ): Boolean {
        // 质量检查
        val qualityCheck = FaceQualityChecker.check(face, bitmap)
        if (!qualityCheck.isQualityAcceptable()) {
            Log.d("FaceSDK", "人脸质量检查失败: ${qualityCheck.getFailureReason()}")
            return false
        }

        // 尺寸检查
        val minFaceSize = Settings.getMinFaceSize(requireContext())
        if (face.boundingBox.width() < minFaceSize || face.boundingBox.height() < minFaceSize) {
            Log.d("FaceSDK", "人脸尺寸过小")
            return false
        }

        // 姿态检查
        if (!FaceQualityChecker.isPoseAcceptable(face)) {
            Log.d("FaceSDK", "人脸姿态不合适")
            return false
        }

        // 光照检查
        val lightingCondition = ImageAnalyzer.getFaceLightingCondition(bitmap, face.boundingBox)
        if (lightingCondition.quality == ImageAnalyzer.LightingQuality.POOR) {
            Log.d("FaceSDK", "光照条件不佳")
            return false
        }

        return true
    }

    private suspend fun performFaceMatching(
        features: FloatArray,
        faceBitmap: Bitmap,
        timestamp: Long
    ): Triple<String, String, Float>? {
        try {
            return withTimeout(1000) { // 1秒超时
                val recognitionThreshold = Settings.getRecognitionThreshold(requireContext())
                val minConfirmations = Settings.getMinConfirmations(requireContext())
                val recognitionInterval = Settings.getRecognitionInterval(requireContext()) * 1000L

                Log.d(
                    "FaceSDK",
                    "开始人脸匹配 - 阈值: $recognitionThreshold, 最小确认次数: $minConfirmations"
                )

                // 1. 先计算所有注册人脸的相似度
                val matchResults = coroutineScope {
                    registeredFaces.map { registeredFace ->
                        async {
                            try {
                                val similarity = faceFeatureExtractor.compareFaces(
                                    features,
                                    registeredFace.faceFeatures
                                )
                                Log.d(
                                    "FaceSDK",
                                    "比对完成 - ID: ${registeredFace.id}, 相似度: $similarity"
                                )
                                
                                // 只返回基本信息
                                Triple(registeredFace.id, registeredFace.name, similarity)
                            } catch (e: Exception) {
                                Log.e(
                                    "FaceSDK",
                                    "人脸比对失败 - ID: ${registeredFace.id}: ${e.message}"
                                )
                                null
                            }
                        }
                    }.mapNotNull { it.await() }
                }

                // 2. 找出最佳匹配
                val bestMatch = matchResults.maxByOrNull { it.third }
                
                // 3. 如果找到最佳匹配且达到阈值，再创建 QuadResult 并更新历史记录
                bestMatch?.let { (id, name, similarity) ->
                    if (similarity >= recognitionThreshold) {
                        // 只在这里创建 QuadResult
                        val quadResult = QuadResult(
                            id = id,
                            name = name,
                            similarity = similarity,
                            history = mutableListOf(),
                            confirmations = 0
                        )
                        
                        // 更新识别历史
                        synchronized(id) {
                            val history = recognitionHistory.getOrPut(id) {
                                mutableListOf()
                            }
                            history.add(similarity)
                            if (history.size > historyMaxSize) {
                                history.removeAt(0)
                            }

                            // 计算历史记录中的确认次数
                            val confirmations = history.count { it >= recognitionThreshold }
                            Log.d(
                                "FaceSDK",
                                "最佳匹配确认统计 - ID: $id, 当前确认次数: $confirmations, 所需确认次数: $minConfirmations"
                            )

                            // 只有在达到确认次数要求时才返回结果
                            if (confirmations >= minConfirmations) {
                                // 达到确认次数后，清空历史记录
                                history.clear()
                                Log.d(
                                    "FaceSDK",
                                    "达到确认次数，重置历史记录 - ID: $id"
                                )

                                // 检查识别时间间隔
                                val lastTime = lastRecognitionTime[id] ?: 0L
                                val timeSinceLastRecord = timestamp - lastTime
                                
                                if (timeSinceLastRecord >= recognitionInterval) {
                                    lastRecognitionTime[id] = timestamp
                                    return@withTimeout Triple(id, name, similarity)
                                } else {
                                    Log.d("FaceSDK", "跳过记录 - 未达到记录间隔")
                                    return@withTimeout null
                                }
                            }
                        }
                    }
                }

                null
            }
        } catch (e: TimeoutCancellationException) {
            Log.e("FaceSDK", "人脸匹配超时")
            null
        } catch (e: Exception) {
            Log.e("FaceSDK", "人脸匹配过程发生错误: ${e.message}")
            null
        }
        return null
    }

    // 添加用于存储匹配结果的数据类
    private data class QuadResult(
        val id: String,
        val name: String,
        val similarity: Float,
        val history: MutableList<Float>,
        val confirmations: Int
    )

    private fun allPermissionsGranted() = ContextCompat.checkSelfPermission(
        requireContext(), Manifest.permission.CAMERA
    ) == PackageManager.PERMISSION_GRANTED

    override fun onResume() {
        super.onResume()
        updateCameraSettings()
    }

    private fun updateCameraSettings() {
        camera?.let { camera ->
            viewLifecycleOwner.lifecycleScope.launch {
                try {
                    // 更新自动对焦
                    val autoFocusEnabled = Settings.isAutoFocusEnabled(requireContext())
                    if (autoFocusEnabled) {
                        // 设置自动对焦点为中心点
                        val factory = SurfaceOrientedMeteringPointFactory(1f, 1f)
                        val point = factory.createPoint(0.5f, 0.5f) // 在预览中心创建对焦点
                        val action = FocusMeteringAction.Builder(point, FocusMeteringAction.FLAG_AF)
                            .setAutoCancelDuration(3, TimeUnit.SECONDS) // 3秒后自动取消对焦
                            .build()
                        camera.cameraControl.startFocusAndMetering(action)
                    }

                    // 更新闪光灯
                    val flashEnabled = Settings.isFlashEnabled(requireContext())
                    camera.cameraControl.enableTorch(flashEnabled)

                    Log.d(
                        TAG, """
                        更新相机设置:
                        自动对焦: $autoFocusEnabled
                        闪光灯: $flashEnabled
                    """.trimIndent()
                    )
                } catch (e: Exception) {
                    Log.e(TAG, "更新相机设置失败: ${e.message}")
                }
            }
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        // 关闭通道
        viewLifecycleOwner.lifecycleScope.launch(NonCancellable) {
            try {
                detectionQueue?.close()
                recognitionQueue?.close()
                Log.d("FaceSDK", "通道已关闭")
            } catch (e: Exception) {
                Log.e("FaceSDK", "关闭通道时发生错误: ${e.message}")
            }
        }
        detectionQueue = null
        recognitionQueue = null
        
        imageAnalyzer = null
        camera = null
        cameraExecutor?.shutdown()
        cameraExecutor = null
        binding.rvRecognizedFaces.adapter = null
        _binding = null
        lastRecognitionTime.clear()
        isProcessing.set(false)
    }

    // 人脸检测分析器
    private class FaceAnalyzer(
        private val listener: (faces: List<com.google.mlkit.vision.face.Face>, bitmap: android.graphics.Bitmap?, rotation: Int) -> Unit,
        private val onUpdateTips: (face: com.google.mlkit.vision.face.Face, bitmap: android.graphics.Bitmap) -> Unit
    ) : ImageAnalysis.Analyzer {
        private val detector = FaceDetection.getClient(
            FaceDetectorOptions.Builder()
                .setPerformanceMode(FaceDetectorOptions.PERFORMANCE_MODE_FAST)
                .setLandmarkMode(FaceDetectorOptions.LANDMARK_MODE_ALL)  // 确保启用所有关键点检测
                .setClassificationMode(FaceDetectorOptions.CLASSIFICATION_MODE_ALL)
                .setContourMode(FaceDetectorOptions.CONTOUR_MODE_ALL)  // 添加轮廓检测
                .setMinFaceSize(0.1f)
                .enableTracking()
                .build()
        )

        @androidx.camera.core.ExperimentalGetImage
        override fun analyze(imageProxy: ImageProxy) {
            val mediaImage = imageProxy.image
            if (mediaImage != null) {
                val rotation = imageProxy.imageInfo.rotationDegrees
                Log.d(
                    "FaceSDK",
                    "开始分析图像 - 分辨率: ${mediaImage.width}x${mediaImage.height}, 旋转: $rotation"
                )
                
                val image = InputImage.fromMediaImage(
                    mediaImage,
                    rotation
                )

                detector.process(image)
                    .addOnSuccessListener { faces ->
                        val bitmap = imageProxy.toBitmap()
                        Log.d("FaceSDK", "检测到原始人脸数量: ${faces.size}")

                        if (faces.isEmpty()) {
                            Log.d("FaceSDK", "未检测到人脸")
                            listener(emptyList(), null, rotation)
                            return@addOnSuccessListener
                        }

                        // 过滤出完整显示在屏幕中的人脸
                        val validFaces = faces.filter { face ->
                            val box = face.boundingBox
                            Log.d(
                                "FaceSDK",
                                "处理人脸 - ID: ${face.trackingId}, 位置: [${box.left},${box.top},${box.right},${box.bottom}]"
                            )

                            // 1. 检查人脸边界框是否完全在图像范围内
                            val isInBounds = box.left >= 0 &&
                                    box.top >= 0 &&
                                    box.right <= bitmap.width &&
                                    box.bottom <= bitmap.height

                            // 2. 检查人脸大小是否合适（不能太小或太大）
                            val faceWidth = box.width().toFloat() / bitmap.width
                            val faceHeight = box.height().toFloat() / bitmap.height
                            Log.d("FaceSDK", "人脸尺寸比例 - 宽度: $faceWidth, 高度: $faceHeight")

                            // 进一步放宽尺寸限制
                            val isSizeValid = faceWidth >= 0.1f && faceWidth <= 0.9f &&
                                    faceHeight >= 0.1f && faceHeight <= 0.9f

                            // 3. 检查人脸是否正面（使用欧拉角）
                            // 进一步放宽角度限制
                            val isGoodPose = abs(face.headEulerAngleY) <= 30 && // 左右转动不超过30度
                                    abs(face.headEulerAngleZ) <= 30 // 歪头不超过30度

                            Log.d(
                                "FaceSDK",
                                "姿态角度 - 左右: ${face.headEulerAngleY}, 歪头: ${face.headEulerAngleZ}"
                            )

                            // 添加详细日志
                            if (!isInBounds) {
                                Log.d("FaceSDK", "人脸超出边界")
                            }
                            if (!isSizeValid) {
                                Log.d("FaceSDK", "人脸尺寸不合适")
                            }
                            if (!isGoodPose) {
                                Log.d("FaceSDK", "人脸姿态不合适")
                            }

                            val isValid = isInBounds && isSizeValid && isGoodPose
                            Log.d(
                                "FaceSDK",
                                "人脸验证结果 - 边界检查: $isInBounds, 尺寸检查: $isSizeValid, 姿态检查: $isGoodPose"
                            )

                            isValid
                        }

                        Log.d("FaceSDK", "过滤后的有效人脸数量: ${validFaces.size}")

                        if (validFaces.isNotEmpty()) {
                            Log.d("FaceSDK", "开始处理有效人脸")
                            try {
                                // 通过回调更新提示信息
                                bitmap?.let { nonNullBitmap ->
                                    onUpdateTips(validFaces[0], nonNullBitmap)
                                }
                                listener(validFaces, bitmap, rotation)
                            } catch (e: Exception) {
                                Log.e("FaceSDK", "处理有效人脸时发生错误: ${e.message}")
                            }
                        } else {
                            Log.d("FaceSDK", "没有找到有效人脸")
                            listener(emptyList(), null, rotation)
                        }
                    }
                    .addOnFailureListener { e ->
                        Log.e("FaceSDK", "人脸检测失败: ${e.message}")
                    }
                    .addOnCompleteListener {
                        imageProxy.close()
                    }
            } else {
                Log.d("FaceSDK", "相机图像为空")
                imageProxy.close()
            }
        }
    }

    private fun bindCameraUseCases(cameraProvider: ProcessCameraProvider) {
        try {
            Log.d(TAG, "开始绑定相机用例")
            
            // 从设置中获取目标分辨率
            val targetResolution = Settings.getCameraResolutionSize(requireContext())
            Log.d(TAG, "目标分辨率: ${targetResolution.width}x${targetResolution.height}")

            // 配置相机预览
            val preview = Preview.Builder()
                .setTargetResolution(targetResolution)
                .build()
                .also {
                    Log.d(TAG, "配置预览完成")
                    it.setSurfaceProvider(binding.viewFinder.surfaceProvider)
                }

            // 配置图像分析器
            Log.d(TAG, "开始配置图像分析器")
            imageAnalyzer = ImageAnalysis.Builder()
                .setTargetResolution(targetResolution)
                .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
                .build()
                .also { analyzer ->
                    Log.d(TAG, "设置图像分析器回调")
                    analyzer.setAnalyzer(
                        cameraExecutor ?: return@also,
                        FaceAnalyzer(
                            listener = { faces, bitmap, rotation ->
                                _binding?.let { binding ->
                                    if (!isProcessingFrame) {
                                        isProcessingFrame = true
                                        val cameraFacing =
                                            Settings.getCameraFacing(requireContext())
                                        val showEyeRect = Settings.isShowEyeRect(requireContext())
                                        Log.d(
                                            TAG, """
                                            更新人脸显示:
                                            人脸数量: ${faces.size}
                                            显示人脸框: ${Settings.isShowFaceRect(requireContext())}
                                            显示眼睛框: $showEyeRect
                                            图像尺寸: ${bitmap?.width}x${bitmap?.height}
                                            旋转角度: $rotation
                                            是否前置相机: ${cameraFacing == CameraSettings.CAMERA_FACING_FRONT}
                                        """.trimIndent()
                                        )
                                        binding.faceOverlayView.updateFaces(
                                            faces,
                                            Settings.isShowFaceRect(requireContext()),
                                            bitmap?.width ?: 0,
                                            bitmap?.height ?: 0,
                                            rotation,
                                            cameraFacing == CameraSettings.CAMERA_FACING_FRONT,
                                            showEyeRect
                                        )

                                        if (faces.isNotEmpty()) {
                                            viewLifecycleOwner.lifecycleScope.launch {
                                                try {
                                                    bitmap?.let { nonNullBitmap ->
                                                        detectionQueue?.send(faces to nonNullBitmap)
                                                    }
                                                } catch (e: Exception) {
                                                    Log.e(TAG, "发送检测任务失败: ${e.message}")
                                                } finally {
                                                    isProcessingFrame = false
                                                }
                                            }
                                        } else {
                                            isProcessingFrame = false
                                        }
                                    }
                                }
                            },
                            onUpdateTips = { face, bitmap ->
                                updateTips(face, bitmap)
                            }
                        )
                    )
                }

            Log.d(TAG, "解绑之前的相机用例")
            cameraProvider.unbindAll()

            Log.d(TAG, "绑定相机用例到生命周期")
            val cameraFacing = Settings.getCameraFacing(requireContext())
            val cameraSelector = when (cameraFacing) {
                CameraSettings.CAMERA_FACING_FRONT -> CameraSelector.DEFAULT_FRONT_CAMERA
                CameraSettings.CAMERA_FACING_BACK -> CameraSelector.DEFAULT_BACK_CAMERA
                else -> CameraSelector.DEFAULT_FRONT_CAMERA
            }
            camera = cameraProvider.bindToLifecycle(
                viewLifecycleOwner,
                cameraSelector,
                preview,
                imageAnalyzer
            )
            Log.d(TAG, "相机初始化完成")

            // 应用相机设置
            camera?.let { camera ->
                // 设置自动对焦
                if (Settings.isAutoFocusEnabled(requireContext())) {
                    val factory = SurfaceOrientedMeteringPointFactory(1f, 1f)
                    val point = factory.createPoint(0.5f, 0.5f) // 在预览中心创建对焦点
                    val action = FocusMeteringAction.Builder(point, FocusMeteringAction.FLAG_AF)
                        .setAutoCancelDuration(3, TimeUnit.SECONDS) // 3秒后自动取消对焦
                        .build()
                    camera.cameraControl.startFocusAndMetering(action)
                }

                // 设置闪光灯
                camera.cameraControl.enableTorch(Settings.isFlashEnabled(requireContext()))
                Log.d(
                    TAG, """
                    应用相机设置:
                    自动对焦: ${Settings.isAutoFocusEnabled(requireContext())}
                    闪光灯: ${Settings.isFlashEnabled(requireContext())}
                """.trimIndent()
                )
            }

            // 设置预览视图尺寸
            binding.viewFinder.post {
                Log.d(TAG, "设置预览视图尺寸: ${binding.viewFinder.width}x${binding.viewFinder.height}")
                binding.faceOverlayView.setPreviewSize(
                    binding.viewFinder.width,
                    binding.viewFinder.height
                )
                binding.faceOverlayView.setShowFaceRect(
                    Settings.isShowFaceRect(requireContext())
                )
                binding.faceOverlayView.setShowEyeRect(Settings.isShowEyeRect(requireContext()))
            }
        } catch (e: Exception) {
            Log.e(TAG, "绑定相机用例失败", e)
        }
    }

    private fun updateRecognitionResult(
        matchResult: Triple<String, String, Float>?,
        faceBitmap: Bitmap
    ) {
        viewLifecycleOwner.lifecycleScope.launch(Dispatchers.Main) {
            try {
                if (matchResult != null) {
                    val (id, name, similarity) = matchResult
                    Log.d(TAG, "更新识别结果 - ID: $id, 姓名: $name, 相似度: $similarity")

                    // 更新状态文本
                    binding.tvTitle.text =
                        "识别到: $name (相似度: ${String.format("%.2f", similarity)})"

                    // 保存识别记录
                    saveRecognitionRecord(name, similarity, faceBitmap)
                } else {
                    //  binding.tvTitle.text = "未识别到匹配的人脸"
                }
            } catch (e: Exception) {
                Log.e(TAG, "更新识别结果失败: ${e.message}")
                binding.tvTitle.text = "识别失败"
            }
        }
    }

    private fun saveRecognitionRecord(
        name: String,
        similarity: Float,
        faceBitmap: Bitmap,
        recognitionTime: Long = System.currentTimeMillis()
    ) {
        viewLifecycleOwner.lifecycleScope.launch {
            try {
                // 确保bitmap没有被回收
                if (faceBitmap.isRecycled) {
                    Log.e(TAG, "人脸图像已被回收，无法保存记录")
                    return@launch
                }

                // 创建bitmap的副本以避免原始bitmap被回收
                val bitmapCopy = try {
                    Bitmap.createBitmap(faceBitmap)
                } catch (e: Exception) {
                    Log.e(TAG, "创建人脸图像副本失败", e)
                    return@launch
                }

                val record = RecognitionRecord(
                    name = name,
                    similarity = similarity,
                    recognitionTime = recognitionTime,
                    faceBitmap = bitmapCopy
                )

                withContext(Dispatchers.IO) {
                    try {
                        FaceDatabase.getDatabase(requireContext())
                            .recognitionRecordDao()
                            .insert(record)
                        Log.d(TAG, "保存识别记录成功：$name, 相似度: $similarity")
                    } catch (e: Exception) {
                        Log.e(TAG, "保存识别记录到数据库失败", e)
                        bitmapCopy.recycle()
                    }
                }
            } catch (e: Exception) {
                Log.e(TAG, "保存识别记录失败", e)
            }
        }
    }

    private fun getLatestRecords(): Flow<List<RecognitionRecord>> {
        return FaceDatabase.getDatabase(requireContext())
            .recognitionRecordDao()
            .getAllRecords()
    }

    private fun updateTips(
        face: com.google.mlkit.vision.face.Face,
        bitmap: android.graphics.Bitmap
    ) {
        viewLifecycleOwner.lifecycleScope.launch(Dispatchers.Main) {
            try {
                val tips = mutableListOf<String>()

                // 检查光照条件
                val lightingCondition =
                    ImageAnalyzer.getFaceLightingCondition(bitmap, face.boundingBox)
                when (lightingCondition.quality) {
                    ImageAnalyzer.LightingQuality.POOR -> tips.add("光照条件不佳，请调整光线")
                    ImageAnalyzer.LightingQuality.FAIR -> tips.add("光照条件一般，建议调整光线")
                    else -> {}
                }

                // 检查姿态
                if (!FaceQualityChecker.isPoseAcceptable(face)) {
                    tips.add("请保持正面朝向摄像头")
                }

                // 检查人脸大小
                val faceWidth = face.boundingBox.width().toFloat() / bitmap.width
                val faceHeight = face.boundingBox.height().toFloat() / bitmap.height
                if (faceWidth < 0.2f || faceHeight < 0.2f) {
                    tips.add("请靠近摄像头")
                } else if (faceWidth > 0.8f || faceHeight > 0.8f) {
                    tips.add("请远离摄像头")
                }

                // 更新提示文本
                if (tips.isNotEmpty()) {
                    binding.tvTips.text = tips.joinToString("\n")
                    binding.tvTips.visibility = View.VISIBLE
                } else {
                    binding.tvTips.visibility = View.GONE
                }
            } catch (e: Exception) {
                Log.e(TAG, "更新提示信息失败: ${e.message}")
            }
        }
    }
} 